//
//  VPSwipeUpInteractiveTransition.m
//  VPPublicUntilitisForPod
//
//  Created by vernepung on 2017/8/25.
//  Copyright © 2017年 vernepung. All rights reserved.
//

#import "VPSwipeUpInteractiveTransition.h"
#import "UtilsMacro.h"
@interface VPSwipeUpInteractiveTransition()
@property (assign, nonatomic) BOOL shouldComplete;
@property (assign, nonatomic) UIViewController *presentingViewController;

@end

@implementation VPSwipeUpInteractiveTransition

- (void)bindToViewController:(UIViewController *)viewController {
    self.presentingViewController = viewController;
    [self prepareGestureRecognizerInView:viewController.view];
}

- (void)prepareGestureRecognizerInView:(UIView*)view {
    UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [view addGestureRecognizer:gesture];
}

//- (UIViewAnimationCurve)completionCurve {
//    return UIViewAnimationCurveEaseInOut;
//}

- (CGFloat)completionSpeed {
    return 1 - self.percentComplete;
}

- (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer{
    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            self.interacting = YES;
            [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            break;
        case UIGestureRecognizerStateChanged:{
            CGFloat fraction = translation.y / (kMainBoundsHeight - kNavBarHeightWithStatusBarHeight);
            fraction = fminf(fmaxf(fraction, 0.0), 1.0f);
            self.shouldComplete = fraction > 0.5;
            [self updateInteractiveTransition:fraction];
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:{
            self.interacting = NO;
            if (!self.shouldComplete || gestureRecognizer.state == UIGestureRecognizerStateCancelled) {
                [self cancelInteractiveTransition];
            } else {
                [self finishInteractiveTransition];
            }
            break;
        }
        default:
            break;
    }
}


@end
